package com.example.demo.utils;

import org.apache.commons.codec.binary.Base64;
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class ImageMergeUtil {

    public static byte[] mergeImages(List<String> base64Images) throws IOException {
        if (base64Images == null || base64Images.isEmpty()) {
            return null;
        }

        // 解析所有图片
        List<BufferedImage> images = new ArrayList<>();
        int totalWidth = 0;
        int maxHeight = 0;

        for (String base64 : base64Images) {
            String pureBase64 = base64.contains(",") ?
                    base64.split(",")[1] : base64;
            byte[] imageBytes = Base64.decodeBase64(pureBase64);
            BufferedImage img = ImageIO.read(new ByteArrayInputStream(imageBytes));

            if (img != null) {
                images.add(img);
                totalWidth += img.getWidth();
                if (img.getHeight() > maxHeight) {
                    maxHeight = img.getHeight();
                }
            }
        }

        // 创建合并后的图片（水平排列）
        BufferedImage combined = new BufferedImage(
                totalWidth, maxHeight, BufferedImage.TYPE_INT_RGB);
        Graphics g = combined.getGraphics();
        g.setColor(Color.WHITE);
        g.fillRect(0, 0, totalWidth, maxHeight);

        // 绘制每张图片
        int x = 0;
        for (BufferedImage img : images) {
            g.drawImage(img, x, (maxHeight - img.getHeight()) / 2, null);
            x += img.getWidth();
        }
        g.dispose();

        // 限制最大高度（增加行高后可以显示更高图片）
        int maxAllowedHeight = 1500; // 像素

        // 如果合并后的图片高度超过限制，等比例缩放
        if (maxHeight > maxAllowedHeight) {
            float scale = (float) maxAllowedHeight / maxHeight;
            int scaledWidth = (int) (totalWidth * scale);
            int scaledHeight = maxAllowedHeight;

            // 创建缩放后的图片
            BufferedImage scaledImage = new BufferedImage(scaledWidth, scaledHeight, BufferedImage.TYPE_INT_RGB);
            Graphics2D g2d = scaledImage.createGraphics();
            g2d.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
            g2d.drawImage(combined, 0, 0, scaledWidth, scaledHeight, null);
            g2d.dispose();

            combined = scaledImage;
            totalWidth = scaledWidth;
            maxHeight = scaledHeight;
        }

        // 转换为字节数组
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ImageIO.write(combined, "png", baos);
        return baos.toByteArray();
    }
}